import 'package:sow_app_core/sow_app_core.dart';

import 'model/ajax_response_model.dart';
import 'model/user_feedback_model.dart';
import 'model/user_info_model.dart';

class AjaxUserRepository implements UserRepository {
  final RestClient client;

  AjaxUserRepository(this.client);

  @override
  Future<String> login(String username, String password) async {
    const path = '/user/login';
    RequestType type = RequestType.post;
    final response = await client.invokeHttp(path, type,
        body: {'username': username, 'password': password});
    return response.data["token"];
  }

  @override
  Future<String> register(String username, String password, int velCode) async {
    const path = '/user/register';
    RequestType type = RequestType.post;
    final AjaxResponseModel response = (await client.invokeHttp(path, type,
        body: {
          'username': username,
          'password': password,
          'velCode': velCode
        }));
    return response.data['token']; // coverage:ignore-line
  }

  @override
  Future<User> info() async {
    const path = '/user/userInfo';
    RequestType type = RequestType.get;
    try {
      final response = await client.invokeHttp(path, type);

      return UserInfoModel.fromJson(response.data).toEntity();
    } on ServerException {
      throw UserNotfoundException();
    }
  }

  @override
  addFeedback(String params) async {
    const path = '/user/addFeedBack';
    RequestType type = RequestType.post;
    await client.invokeHttp(path, type, body: {
      'content': params,
    });
  }

  @override
  changePassword(String oldPass, String newPass) async {
    const path = '/user/updatePassword';
    RequestType type = RequestType.post;
    await client.invokeHttp(path, type, body: {
      'oldPassword': oldPass,
      'newPassword1': newPass,
      'newPassword2': newPass
    });
  }

  @override
  Future<List<Feedback>> getFeedbackList() async {
    const path = '/user/listUserFeedBackByPage';
    RequestType type = RequestType.get;
    final response =
        await client.invokeHttp(path, body: {"limit": '99999'}, type);
    return (response.data['list'] as List)
        .map<Feedback>((e) => UserFeedbackModel.fromJson(e).toEntity())
        .toList();
  }
}
